import type { Account, LoginResponse } from '@/api/UserAccountApi.ts'
import type { PersistencePluginOption } from '@/config/store/PersistencePlugin.ts'
import { StrTool } from '@es-tool/core'
import { defineStore } from 'pinia'
import { computed, type ComputedRef, ref } from 'vue'

/**
 * 登录账户
 */
export const useAccountStore = defineStore(
        '登录账户',
        () => {
            const access = ref('')
            const refresh = ref('')
            const account = ref<Account>({} as any)

            const onLogin = (loginResponse: LoginResponse) => {
                access.value = loginResponse.access?.token ?? ''
                refresh.value = loginResponse.refresh?.token ?? ''
                account.value = loginResponse.account ?? {} as any
            }

            const isLogin: ComputedRef<boolean> = computed(() => StrTool.isNotEmpty(access.value))

            const updateAccountInfo = (value: Account) => account.value = value

            const clearAccessToken = () => access.value = ''

            return {
                access,
                refresh,
                account,
                isLogin,
                onLogin,
                clearAccessToken,
                updateAccountInfo,
            }
        },
        {
            persistencePlugin: {
                persistence: true,
                eternal: true,
            } as PersistencePluginOption,
        },
)
